import cv2
import numpy as np
# nw/Pic_20241218150353779.bmp
# 读取图像并转换为灰度图
img = cv2.imread('nw/Pic_20241218152515939.bmp', cv2.IMREAD_GRAYSCALE)

# 将灰度图转换为三通道图像
img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

# 使用 Harris 角点检测，调整参数
dst = cv2.cornerHarris(img, blockSize=5, ksize=3, k=0.04)

# 非极大值抑制
def non_max_suppression(dst, window_size=3):
    dst_max = cv2.dilate(dst, np.ones((window_size, window_size)))
    dst[dst < dst_max] = 0
    return dst

dst = non_max_suppression(dst)

# 获取角点坐标
corners = np.argwhere(dst > 0.01 * dst.max())
corners = [tuple(corner) for corner in corners[:, ::-1]]  # 转换为 (x, y) 格式

# 筛选角点
def filter_corners(corners, neighborhood_radius=10):
    filtered_corners = []
    used = set()

    for i, (x1, y1) in enumerate(corners):
        if (x1, y1) in used:
            continue

        # 查找邻域内的其他角点
        neighbors = []
        for j, (x2, y2) in enumerate(corners):
            if i == j:
                continue
            if abs(x1 - x2) <= neighborhood_radius and abs(y1 - y2) <= neighborhood_radius:
                neighbors.append((x2, y2))

        # 根据邻域内角点数量处理
        if len(neighbors) == 0:
            # 没有邻域点，认为是边缘角点，舍弃
            continue
        elif len(neighbors) == 1:
            x2, y2 = neighbors[0]
            # 有一个邻域点，计算中点
            x_mid = (x1 + x2) // 2
            y_mid = (y1 + y2) // 2
            filtered_corners.append((x_mid, y_mid))
            used.add((x1, y1))
            used.add((x2, y2))


    return filtered_corners

# 筛选角点
filtered_corners = filter_corners(corners)

# 在图像上标记筛选后的角点
for (x, y) in filtered_corners:
    cv2.circle(img_color, (x, y), 1, (0, 0, 255), -1)

# 显示结果
cv2.imshow('Filtered Harris Corner Detection', img_color)
cv2.waitKey(0)
cv2.destroyAllWindows()